package com.corpgovernment.permission.utils;

import com.ctrip.corp.obt.async.redis.RedisClientDelegate;
import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.TypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author zl.cui
 * @date 2023/12/13
 */
@Slf4j
@Component
public class PermissionRedisUtil {
    @Autowired
    private RedisClientDelegate redisClientDelegate;
    public <T> Map<String, T> getCacheHash(String key, final Class<T> tClass) {

            return (Map)this.redisClientDelegate.withHashCommandsClient((c) -> {
                Map map = Maps.newHashMap();

                try {
                    ScanOptions scanOptions = ScanOptions.scanOptions().count(1000L).build();
                    Cursor<Map.Entry<String, Object>> cursor = c.scan(key, scanOptions);

                    while(cursor.hasNext()) {
                        Map.Entry<String, Object> entry = (Map.Entry)cursor.next();
                        map.put(entry.getKey(), entry.getValue());
                    }
                    cursor.close();
                } catch (Exception var7) {
                    log.error("Redis hash paging error:", var7);
                }
                log.info("Execute new getHash command: {}", Optional.ofNullable(RequestContext.getCurrentContext().getRequest()).map((r) -> {
                    return r.getRequestURI();
                }).orElse("Unknown"));
                return map;
            }, new TypeReference<Map<String, T>>() {
                public Type getType() {
                    return TypeUtils.parameterize(Map.class, new Type[]{String.class, tClass});
                }
            });


    }

    public Boolean delCacheHash(String key) {

        return this.redisClientDelegate.withKeyDelete(key);


    }
}
